/*
 * @Autor Wei
 * @Date 2020-04-11 15:54:29
 * @LastEditors Wei
 * @LastEditTime 2020-06-04 11:54:36
 */

const express = require('express');
const router = express.Router();
var multer = require("multer");
const fs = require('fs');
const path = require('path');
const commodity = require('../model/commodity')

// 这里dest对应的值是你要将上传的文件存的文件夹
// var upload = multer({dest:'./public/images'});
// 使用硬盘存储模式设置存放接收到的文件的路径以及文件名
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    // 接收到文件后输出的保存路径（若不存在则需要创建）
    cb(null, path.join(__dirname, "../public/images/commodity/"));
  },
  filename: function (req, file, cb) {
    // 将保存文件名设置为 时间戳 + 文件原始名，比如 151342376785-123.jpg
    let extname = file.mimetype.split('/')[1];
    let imgname = Date.now() + parseInt(Math.random() * 999) + parseInt(Math.random() * 2222);
    let keepname = imgname + '.' + extname

    cb(null, keepname);
  }
});

// 创建 multer 对象
var upload = multer({
  storage: storage
});

router.post('/api/v1/uploadImageTest', upload.fields([{
  name: 'textimg'
}, {
  name: 'mainimg'
}]), function (req, res) {

  let filesData = req.files
  let formData = JSON.parse(req.body.formData)

  filesData.mainimg.forEach(el => {
    formData.mainimg.push(el.filename)
  })

  filesData.textimg.forEach(el => {
    formData.textimg.push(el.filename)
  })
  const info = new commodity(formData);
  info.save(function (err) {
    if (err) {
      console.log(err);
      res.status(500).send(err);
    } // 已保存 
    res.json({
      code: 200,
      data: 'succse'
    })
  });
})

router.post('/api/v1/put_uploadImageTest', upload.fields([{
  name: 'textimg'
}, {
  name: 'mainimg'
}]), function (req, res) {
  console.log(req.files);
  let filesData = req.files
  let formData = JSON.parse(req.body.formData)
  console.log(formData)
  let deleImgArr = []
  if (req.body.deleImgArr) {
    deleImgArr = JSON.parse(req.body.deleImgArr)
  }
  if (filesData.mainimg) {
    filesData.mainimg.forEach(el => {
      console.log(el)
      console.log(formData.mainimg)
      console.log('mainimg')
      formData.mainimg.push(el.filename)
    })
  }

  if (filesData.textimg) {
    filesData.textimg.forEach(el => {
      console.log(el)
      console.log('textimg')
      console.log(formData.textimg)
      formData.textimg.push(el.filename)
    })
  }
  commodity.updateOne({
    _id: formData._id
  }, formData, function (err) {
    if (err) {
      console.log(err);
      res.status(500).send(err);
    }
    if (deleImgArr.length != 0) {
      deleImgArr.forEach(item => {
        fs.unlink(path.join(__dirname, '../public/images/commodity/' + item), function (error) {
          if (error) {
            console.log(error);
            return false;
          }
          console.log('删除文件成功');
        })
      })
    }
    res.json({
      code: 200,
      data: formData
    })
  })
})

module.exports = router